﻿using System.ComponentModel;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Jack.DataScience.Http.Jwt;
using Vav.Api.Utils;
using Vav.Api.GenericDtos;
using Vav.Data.TransferTypes;
using Newtonsoft.Json;
using Vav.Data.Models;
using Vav.Data.DataAccess;
using System;
using Vav.Api.Authorization;
using System.Threading.Tasks;
using System.IO;
using Vav.Data.WeChat;

namespace Vav.Api
{
    [Route("api/wx")]
    public class WeChatController : BaseController
    {
        private readonly WeChatDataAccess weChatDataAccess;
        public WeChatController(WeChatDataAccess weChatDataAccess)
        {
            this.weChatDataAccess = weChatDataAccess;
        }
        [Route("getaccess_token")]
        [HttpGet]
        public async Task<ActionResult<ApiBaseModel>> GetAccessToken(string appid)
        {
            if (string.IsNullOrWhiteSpace(appid))
            {
                return ApiFail("参数错误");
            }
            var data = await weChatDataAccess.GetAccessToken(appid);
            if (string.IsNullOrWhiteSpace(data))
            {
                return ApiFail("获取access_token失败");
            }
            return ApiSuccess(data, "success");
        }
        /// <summary>
        /// 获取公众号用户信息
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="code">网页授权后code</param>
        /// <returns></returns>
        [Route("getpub_userinfo")]
        [HttpGet]
        public async Task<ActionResult<ApiBaseModel>> GetWeChatPubUserInfo(string appid, string code)
        {
            if (string.IsNullOrWhiteSpace(appid) || string.IsNullOrWhiteSpace(code))
            {
                return ApiFail("参数错误");
            }
            var data = await weChatDataAccess.GetWeChatPubUserInfo(appid, code);
            if (data != null && data.errcode == 0)
            {
                return ApiSuccess(data);
            }
            return ApiFail(data.errmsg);
        }
        /// <summary>
        /// 获取小程序用户信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [Route("getpro_userinfo")]
        [HttpPost]
        public async Task<ActionResult<ApiBaseModel>> GetWeChatProUserInfo([FromBody]GetWeChatProUserInfoRequest req)
        {
            if (string.IsNullOrWhiteSpace(req.appid) || string.IsNullOrWhiteSpace(req.code)
                || string.IsNullOrWhiteSpace(req.encryptedData) || string.IsNullOrWhiteSpace(req.iv))
            {
                return ApiFail("参数错误");
            }
            var data = await weChatDataAccess.GetWeChatProUserInfo(req.appid, req.code, req.encryptedData, req.iv);
            if (data != null)
            {
                return ApiSuccess(data);
            }
            return ApiFail("获取userInfo失败");
        }
        /// <summary>
        /// 获取小程序用户手机号
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [Route("getpro_userphone")]
        [HttpPost]
        public async Task<ActionResult<ApiBaseModel>> GetWeChatProUserPhone([FromBody]GetWeChatProUserInfoRequest req)
        {
            if (string.IsNullOrWhiteSpace(req.appid) || string.IsNullOrWhiteSpace(req.code)
                || string.IsNullOrWhiteSpace(req.encryptedData) || string.IsNullOrWhiteSpace(req.iv))
            {
                return ApiFail("参数错误");
            }
            var data = await weChatDataAccess.GetWeChatProUserPhone(req.appid, req.code, req.encryptedData, req.iv);
            if (data != null)
            {
                return ApiSuccess(data);
            }
            return ApiFail("获取用户手机号失败");
        }
        /// <summary>
        /// 获取小程序openId 以及UnionId
        /// </summary>
        /// <param name="appid">appid</param>
        /// <param name="code">小程序code</param>
        /// <returns></returns>
        [Route("getpro_unionid")]
        [HttpGet]
        public async Task<ActionResult<ApiBaseModel>> GetWeChatProUnionId(string appid, string code)
        {
            if (string.IsNullOrWhiteSpace(appid) || string.IsNullOrWhiteSpace(code))
            {
                return ApiFail("参数错误");
            }
            var data = await weChatDataAccess.GetProUserUnionId(appid, code);
            if (data.errcode == 0)
            {
                return ApiSuccess(data);
            }
            return ApiFail(data.errmsg);
        }
        /// <summary>
        /// 获取小程序二维码
        /// </summary>
        /// <param name="appid">appid</param>
        /// <param name="scene">页面参数</param>
        /// <param name="page">页面路径</param>
        /// <returns></returns>
        [Route("getpro_code")]
        [HttpGet]
        public async Task<ActionResult<ApiBaseModel>> GetProCode(string appid, string scene, string page)
        {
            if (string.IsNullOrWhiteSpace(appid) || string.IsNullOrWhiteSpace(scene)
                || string.IsNullOrWhiteSpace(page))
            {
                return ApiFail("参数错误");
            }
            var token = await weChatDataAccess.GetAccessToken(appid);
            var data = await weChatDataAccess.GetProCode(token, scene, page);
            if (data.Length > 10000)
            {
                return new FileStreamResult(data, "image/png");
            }
            else
            {
                using (StreamReader reader = new StreamReader(data))
                {
                    string text = reader.ReadToEnd();
                    var result = JsonConvert.DeserializeObject<ErrorResponse>(text);
                    if (result.errcode != 0)
                    {
                        return ApiFail(result.errmsg);
                    }
                }
            }
            return ApiFail("请求失败");
        }
        /// <summary>
        /// 公众号推送模板消息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [Route("sendpub_msg")]
        [HttpPost]
        public async Task<ActionResult<ApiBaseModel>> SendPubTemplateMsg([FromBody] SendPubTemplateMsgRequest req)
        {
            if (string.IsNullOrWhiteSpace(req.appid) || req.data == null)
            {
                return ApiFail("参数错误");
            }
            var token = await weChatDataAccess.GetAccessToken(req.appid);
            if (!string.IsNullOrWhiteSpace(token))
            {
                var result = await weChatDataAccess.SendPubTemplateMsg(token, req.data);
                if (result.errcode == 0)
                {
                    return ApiSuccess(result.errmsg);
                }
                return ApiFail(result.errmsg);
            }
            return ApiFail("Access_Token不存在");
        }
    }
}
